package com.example.utils;

import java.net.*;
import java.util.*;


public class VirtualSensor {

    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    //1. 建立一个socket
                    DatagramSocket socket = new DatagramSocket();
                    //2. 指定发送地址
                    InetAddress address = InetAddress.getByName("localhost");
                    int port = 9090;
                    //3. 建立数据包
                    Random random = new Random();
                    Double[] temperatures = new Double[2];
                    // 最高气温均值为23，方差为9
                    double highTemp = 23d + random.nextGaussian() * 3;
                    // 最低气温为最高气温减去(0~10)
                    double lowTemp = highTemp - random.nextDouble() * 10;
                    byte[] msg = String.format("%.3f %.3f", highTemp, lowTemp).getBytes();
                    DatagramPacket packet = new DatagramPacket(msg, 0, msg.length, address, port);
                    //4. 发送数据包
                    socket.send(packet);
                    System.out.printf("发送数据：最高温：%.3f 最低温：%.3f%n", highTemp, lowTemp);
                    //5. 关闭连接
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 10, 5000);// 每5秒执行一次
    }
}
